package com.cvticketvender;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.cvricevender.R;
import com.google.gson.Gson;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;

import cv.vender.PrinterUtil;
import cv.vender.QRCodeUtil;
import cv.vender.clsArgs;
import cv.vender.clsCmdConst;
import cv.vender.clsErrorConst;
import cv.vender.clsPublicPara;
import cv.vender.clsSound;
import cv.vender.clsSwipeResult;
import cv.vender.clsToolBox;
import cv.vender.clsTradeTypeConst;
import cv.vender.http.bean.clsSendTradeToPc;
import cv.vender.http.bean.clsVenderBean;
import cv.vender.http.clsHttpFrame;
import cv.vender.http.clscvhttp;
import cv.vender.para.clsCardSnPara;
import cv.vender.para.clsPcPollCreditPara;
import cv.vender.para.clsPcPollPara;
import cv.vender.para.clsPcSubCreditPara;
import cv.vender.para.clsProductPara;
import cv.vender.para.clsStatisticPara;
import cv.vender.para.clsTradeMsgToMcu;
import cv.vender.para.clsTradeTypeStatistic;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
@SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity {
    private static final String CHAR_CODE = "GBK";
    int price = 1600;
    String select_name = null;
    int slotid = 0;
    //boolean EnterTrade=false;
    //boolean EnterTrasfor=false;
    Button but_exit_trade = null;
    ImageView img_al_qrcode = null;
    ImageView img_wx_qrcode = null;
    int time_count_for_back = 0;
    clsSendTradeToPc public_transforing_trade = null;
    Toast toast = null;
    VideoView videoViewBox;
    int make_sound_wel_interval_time = 200;
    private Handler mainHandler;
    private Handler m_brd_Handler;
    private TextView lable_amount = null;
    private TextView lable_weight = null;

    /*交易相关参数*/
    private TextView lable_no = null;
    private FrameLayout view_mask = null;
    private FrameLayout right_parent = null;
    private ImageView image_log = null;
    private TextView lable_credit = null;
    private TextView lable_price = null;
    private TextView lable_shop_name = null;
    private TextView lable_title = null;
    private TextView labFaultTips = null;
    private ArrayList<String> Vediolst;
    private boolean netstate = false;
    private boolean brdstate = false;
    private int getQrcodeTime = 5;//启动5S后，在小票机主板连接的情况下，可以获取二维码
    private int MaxGetQrcodeTime = 3600;//在第一次获取之后，每隔1个小时从新获取一次二维码
    private int BillEn = 0xffff;
    private int CoinEn = 0xffff;

    private boolean lAlEn = true;
    private boolean lWxEn = true;


    public void ShowToast(String textstr) {
        //获取LayoutInflater对象，该对象能把XML文件转换为与之一直的View对象
        LayoutInflater inflater = getLayoutInflater();
        //根据指定的布局文件创建一个具有层级关系的View对象
        //第二个参数为View对象的根节点，即LinearLayout的ID
        View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

        TextView text = layout.findViewById(R.id.text);
        text.setTextSize(32);
        text.setText(textstr);

        if (toast == null) {
            toast = new Toast(getApplicationContext());
        }
        //设置Toast的位置
        toast.setGravity(Gravity.BOTTOM, 0, 50);
        toast.setDuration(Toast.LENGTH_LONG);
        //让Toast显示为我们自定义的样子
        toast.setView(layout);
        toast.show();
    }

    @SuppressLint({"HandlerLeak", "DefaultLocale"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        //lable_amount=(TextView)findViewById(R.id.lable_amount);
        lable_title = findViewById(R.id.lable_title);
        img_al_qrcode = findViewById(R.id.al_qrcode);//支付宝二维码
        lable_shop_name = findViewById(R.id.lable_shop_name);//店铺名称
        img_wx_qrcode = findViewById(R.id.wx_qrcode);//微信二维码
        right_parent = findViewById(R.id.right_parent);
        lable_credit = findViewById(R.id.lable_credit);
        lable_no = findViewById(R.id.lable_no);
        lable_price = findViewById(R.id.lable_price);
        labFaultTips = findViewById(R.id.FaultTips);

        videoViewBox = findViewById(R.id.videoViewBox);
        //重定向输出流
        //System.setOut(new FileOutputStream());
        lable_title = findViewById(R.id.lable_title);
        try {
            //一开始进来先加载参数 没有就创建
            clsArgs.loadargs(this);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        //序号参数
        if (clsPublicPara.XuhaoPara == null) {
            clsPublicPara.XuhaoPara = new clsTradeMsgToMcu();
            clsPublicPara.XuhaoPara.setTotal(new clsTradeTypeStatistic());
            clsPublicPara.XuhaoPara.setCash(new clsTradeTypeStatistic());
            clsPublicPara.XuhaoPara.setWeixin(new clsTradeTypeStatistic());
            clsPublicPara.XuhaoPara.setAlipay(new clsTradeTypeStatistic());
        }

        //加载本地录音资源
        clsSound.LoadSound(this);

        //获取sd卡资源
        ArrayList<String> sdcardlst = clsToolBox.getExtSDCardPath();

        if (sdcardlst.size() > 0) {
            String sd_path = sdcardlst.get(0);
            ShowVedio(sd_path);

            File f = new File(sd_path + "/" + clsArgs.getInst().getImgae_log_file());
            if (f.exists()) {
                Bitmap bitmap = clsToolBox.getLoacalBitmap(f);
                image_log.setImageBitmap(bitmap);
            }
        }

        clsPublicPara.activity = this;

        //机器界面部分参数
        if (clsPublicPara.VenderBean == null) {
            clsPublicPara.VenderBean = new clsVenderBean();
            clsPublicPara.VenderBean.setBILLStat(0);//纸币器状态
            clsPublicPara.VenderBean.setVid(clsArgs.getInst().getVenderid());//设置机器编号
            clsPublicPara.VenderBean.setVer(clsToolBox.ParseInt(clsToolBox.getAppVersionName(this)));//设置版本号
        }
        lable_no.setText(String.format("NO.:%d 版本:%s", clsPublicPara.VenderBean.getVid(), clsToolBox.getAppVersionName(this)));

        PrinterUtil ins = new PrinterUtil();
        //打开打印机
        ins.OpenPrinter(clsArgs.getInst().getPrinter_commid(), clsArgs.getInst().getPrinter_baudrate());
        PrinterUtil.setInst(ins);//设置打印机对象

        ThreadForBrd t_ins = ThreadForBrd.getInstence();//实例化线程管理类
        ThreadForBrd.OpenIns(clsArgs.getInst().getCommid(), clsArgs.getInst().getBaudrate());//打开通信串口

        PrinterUtil.getInst().lTitle = clsArgs.getInst().getTitle();//打印店铺名称
        PrinterUtil.getInst().WelcomTips = clsArgs.getInst().getmWelcomTips();//打印欢迎词

        lable_shop_name.setText(clsArgs.getInst().getTitle());////设置店铺名称

        //加载产品表格
        final ArrayList<clsProductPara> productlst = LoadProduct();
        clsPublicPara.productlst = productlst;

        if (productlst.size() <= 0) {
            ShowToast("没有产品数据，请进入设置创建,否则不能正常使用！");
        } else {
            //有产品 设置价格和序号
            lable_price.setText(String.format("%1.2f", clsPublicPara.productlst.get(0).getPrice() / 100.0));
            lable_title.setText(String.format("当前序号:%d", 0));
        }

        BillEn = clsArgs.getInst().getBills();
        CoinEn = clsArgs.getInst().getCoins();
        lAlEn = clsArgs.getInst().isUseAl();
        lWxEn = clsArgs.getInst().isUseWx();


        mainHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case clsCmdConst.CMD_REPORT_PRINT_ERR:
                            //上报打印机错误
                            //播放提示音

                            //clsSound.makeSound(clsSound.net_err);
                            if (clsPublicPara.VenderBean.getPrintErr() != msg.arg1) {
                                clsPublicPara.VenderBean.setPrintErr(msg.arg1);
                                clsHttpFrame.SendHttpVenderFrame();
                            }
                            if (msg.arg1 == clsErrorConst.ERR_PRINT_NO_RESPONSE) {
                                ShowToast("打印机无响应，请检查通信线路");
                            } else if (msg.arg1 == clsErrorConst.ERR_PRINT_NO_PAPER) {
                                ShowToast("打印机缺纸，请更换打印纸");
                            } else if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {

                            } else {
                                ShowToast(String.format("打印机其他故障，故障码%d", msg.arg1));
                            }
                            break;
                        case clsCmdConst.CMD_PC_POLL:

                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                if (msg.obj != null) {
                                    clsPcPollPara pcPollPara = (clsPcPollPara) msg.obj;
                                    if ((pcPollPara.getEvent() & (1 << 2)) != 0) {
                                        // TODO: 2017-01-06 进入到设置界面
                                        EnterSettingPage();
                                    } else if ((pcPollPara.getEvent() & (1 << 3)) != 0) {
                                        clsStatisticPara sPara = new clsStatisticPara();

                                        sPara.setT_tradecount(clsPublicPara.XuhaoPara.getTotal().getBishu());
                                        sPara.setT_tradebill(clsPublicPara.XuhaoPara.getTotal().getJine());
                                        sPara.setT_ca_tradecount(clsPublicPara.XuhaoPara.getCash().getBishu());
                                        sPara.setT_ca_tradebill(clsPublicPara.XuhaoPara.getCash().getJine());
                                        sPara.setT_wx_tradecount(clsPublicPara.XuhaoPara.getWeixin().getBishu());
                                        sPara.setT_wx_tradebill(clsPublicPara.XuhaoPara.getWeixin().getJine());
                                        sPara.setT_al_tradecount(clsPublicPara.XuhaoPara.getAlipay().getBishu());
                                        sPara.setT_al_tradebill(clsPublicPara.XuhaoPara.getAlipay().getJine());
                                        Calendar c = Calendar.getInstance();
                                        c.setTimeInMillis(clsPublicPara.XuhaoPara.getStart_timestamp());
                                        sPara.setLasttime(c);
                                        PrinterUtil.getInst().PrintTradeStatistic(sPara);

                                        clsPublicPara.XuhaoPara.Clr();
                                        //// TODO: 2018/1/28 添加统计小票打印功能，已经添加完成

                                        ThreadForBrd.getInstence().SetTradeMsg(clsPublicPara.XuhaoPara);
                                    }
                                    int bill_state = pcPollPara.getBill_state();
                                    if (clsPublicPara.VenderBean.getBILLStat() != bill_state) {
                                        clsPublicPara.VenderBean.setBILLStat(bill_state);//纸币器状态
                                        clsHttpFrame.SendHttpVenderFrame();
                                    }

                                    //刷新投入金额
                                    lable_credit.setText(String.format("%1.2f", (double) pcPollPara.getCurrent_credit() / 100));

                                    if (pcPollPara.getCurrent_credit() > 0) {
                                        clsProductPara productpara = productlst.get(0);
                                        if (productpara.getPrice() <= pcPollPara.getCurrent_credit()) {
                                            //剪掉相应金额
                                            ThreadForBrd.getInstence().SubSomeCredit(productpara.getPrice());
                                        }
                                    }
                                }
                                if (!brdstate) {
                                    ThreadForBrd.getInstence().SendPcLnkRequest();
                                }
                                brdstate = true;
                            } else {
                                ShowToast(String.format("主板通信故障,无法接收现金，错误码%d", msg.arg1));
                                brdstate = false;
                            }
                            ThreadForBrd.getInstence().StartPcPoll();

                            break;
                        case clsCmdConst.CMD_HTTP_SWIPE_DATA_PARSE:

                            // TODO: 2017-01-06 解析刷卡返回数据
                            if (msg.arg1 == 1) {
                                String res = (String) msg.obj;//SWIPE结果代码，价格，交易编号，货道编号,卡内余额
                                String[] res_arr = res.split(",", -1);
                                TextView ic_card_tips = findViewById(R.id.ic_card_tips);
                                if (res_arr.length > 1) {
                                    int swiperes = clsToolBox.ParseInt(res_arr[0].substring(5));
                                    if (swiperes == clsSwipeResult.CUSTOMER_OK) {
                                        int price = clsToolBox.ParseInt(res_arr[1]);
                                        clsSendTradeToPc swipe_trade = new clsSendTradeToPc();
                                        swipe_trade.setTradeId(res_arr[2]);
                                        int balance = clsToolBox.ParseInt(res_arr[4]);
                                        if (ic_card_tips != null) {
                                            ic_card_tips.setText(String.format("刷卡成功,卡内余额:%1.2f元", balance / 100.0));
                                        }
                                        clsHttpFrame.SendHttpPollFrame();
                                    } else {
                                        if (ic_card_tips != null) {
                                            ic_card_tips.setText(String.format("刷卡失败，%s,请重试", clsSwipeResult.DES[swiperes]));
                                            ThreadForBrd.getInstence().StartGetCardSn();
                                        }
                                    }
                                }
                            }

                            break;
                        case clsCmdConst.CMD_START_READ_CARD_POLL:
                            //开始读卡片
                            ThreadForBrd.getInstence().StartGetCardSn();
                            break;
                        case clsCmdConst.CMD_PC_GET_CARDSN:
                            //讀取卡片的序列號
                            clsCardSnPara cardSnPara = (clsCardSnPara) msg.obj;
                            TextView ic_card_tips = findViewById(R.id.ic_card_tips);
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                //ShowToast("获取卡号成功,卡号："+cardSnPara.getCardSn());

                                if (cardSnPara.isSuccess()) {
                                    if (ic_card_tips != null) {
                                        ic_card_tips.setText(String.format("卡号:%s,正在扣款...", cardSnPara.getCardSn()));
                                        //启动到服务器扣款
                                        clsSendTradeToPc swipe_trade = new clsSendTradeToPc();

                                        swipe_trade.setUser(cardSnPara.getCardSn());
                                        clsHttpFrame.SendHttpSwipeTradeRequest(swipe_trade);
                                    }
                                } else {
                                    ThreadForBrd.getInstence().StartGetCardSn();
                                }
                            } else {
                                if (ic_card_tips != null) {
                                    ic_card_tips.setText(String.format("读卡失败,请重试,故障码%d", msg.arg1));
                                }
                            }


                            break;
                        case clsCmdConst.CMD_START_CREDTI_POLL:

                            ThreadForBrd.getInstence().StartCreditPoll();
                            break;
                        case clsCmdConst.CMD_PC_MDB_SUB_CREDIT:
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                clsPcSubCreditPara pcsubcreditpara = (clsPcSubCreditPara) msg.obj;
                                clsSendTradeToPc public_trade = null;
                                if (public_trade == null) {
                                    public_trade = new clsSendTradeToPc();
                                    clsProductPara productpara = productlst.get(0);
                                    public_trade.setCashAmount(productpara.getPrice());
                                    public_trade.setVendId(clsPublicPara.VenderBean.getVid());
                                    public_trade.setDatetime(Calendar.getInstance());
                                    public_trade.setErr(0);
                                    public_trade.setGoodsname(productpara.getName());
                                    public_trade.setPayTyp(clsTradeTypeConst.TRADE_TYPE_CASH);
                                    public_trade.setSlotid(productpara.getId());
                                    public_trade.setTradeId(clsToolBox.MakeRPID());
                                }

                                public_trade.setPutBills(pcsubcreditpara.getSubCredit());
                                // TODO: 2017-01-05 投入金额达到所需金额，可以出货
                                public_trade.setPaid(1);

                                ThreadForBrd.getInstence().SetCashType(0, 0);
                                public_trade.setPaid(1);
                                this.obtainMessage(clsCmdConst.CMD_PC_TRANSFOR, public_trade).sendToTarget();
                                public_trade = null;
                            }
                            break;
                        case clsCmdConst.CMD_PC_CREDIT:     //获取投入金额
                            clsPcPollCreditPara PcPollCreditPara = (clsPcPollCreditPara) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                TextView cash_credit_tips = findViewById(R.id.cash_credit_tips);

                                int credit = PcPollCreditPara.getCredit();
                                if (cash_credit_tips != null) {
                                    cash_credit_tips.setText(String.format("已投入金额：%d元", credit / 100));
                                }

                            } else {
                                TextView cash_tips = findViewById(R.id.cash_tips);
                                if (cash_tips != null) {
                                    cash_tips.setText(String.format("获取现金金额故障，故障码%d", msg.arg1));
                                }
                            }

                            break;
                        case clsCmdConst.CMD_PC_LNK:  //获取序号信息，交易笔数信息，统计起始时间和统计结束时间
                            ThreadForBrd.getInstence().GetTradeMsg();
                            ThreadForBrd.getInstence().SetCashType(BillEn, CoinEn);
                            ThreadForBrd.getInstence().ClearAllCredit();
                            break;
                        case clsCmdConst.CMD_PC_LOAD_TRADE_MSG:  //加载交易序号，加载起始交易时间和最后交易时间，加载交易总笔数，现金笔数，微信笔数
                            clsTradeMsgToMcu tradeMsgToMcu = (clsTradeMsgToMcu) msg.obj;
                            if (msg.arg1 == clsErrorConst.MDB_ERR_NO_ERR) {
                                if (tradeMsgToMcu != null) {

                                    clsPublicPara.InitialOk = true;

                                    if (clsPublicPara.XuhaoPara.getXuhao() == 0) {
                                        clsPublicPara.XuhaoPara.setXuhao(tradeMsgToMcu.getXuhao());

                                        clsPublicPara.XuhaoPara.getTotal().CopyObj(tradeMsgToMcu.getTotal());
                                        clsPublicPara.XuhaoPara.getCash().CopyObj(tradeMsgToMcu.getCash());
                                        clsPublicPara.XuhaoPara.getWeixin().CopyObj(tradeMsgToMcu.getWeixin());
                                        clsPublicPara.XuhaoPara.getAlipay().CopyObj(tradeMsgToMcu.getAlipay());

                                        clsPublicPara.XuhaoPara.setStart_timestamp(tradeMsgToMcu.getStart_timestamp());
                                        clsPublicPara.XuhaoPara.setEnd_timestamp(tradeMsgToMcu.getEnd_timestamp());
                                    }
                                    lable_title.setText(String.format("当前序号:%d", clsPublicPara.XuhaoPara.getXuhao()));
                                    ShowToast("获取序号ID参数成功");
                                }
                            } else {
                                ShowToast("获取序号ID参数失败，请检查串口连接，并重启机器");
                            }

                            break;
                        case clsCmdConst.CMD_PC_TRANSFOR:   //上位机通知下位机出货
                            clsSendTradeToPc sendTradePara = (clsSendTradeToPc) msg.obj;
                            if (sendTradePara != null) {
                                int xuhao = clsPublicPara.XuhaoPara.getXuhao();
                                sendTradePara.setLiushuiID(xuhao++);
                                if (xuhao > 999) {
                                    xuhao = 1;
                                }
                                clsPublicPara.XuhaoPara.setXuhao(xuhao);
                                ShowToast(String.format("正在出票，编号%d", sendTradePara.getLiushuiID()));
                                PrinterUtil.getInst().StartPrintContent(sendTradePara);
                            }


                            Message t_msg = this.obtainMessage(clsCmdConst.CMD_PC_TRANSFOR_COMPLETE, sendTradePara);
                            this.sendMessageDelayed(t_msg, 2000);

                            break;

                        case clsCmdConst.CMD_PC_TRANSFOR_COMPLETE: //交易完成
                            sendTradePara = (clsSendTradeToPc) msg.obj;
                            lable_title.setText(String.format("当前序号:%d", clsPublicPara.XuhaoPara.getXuhao()));
                            clsHttpFrame.SendHttpTradeFrame(sendTradePara);
                            ThreadForBrd.getInstence().SetCashType(BillEn, CoinEn);
                            clsTradeMsgToMcu spara = clsPublicPara.XuhaoPara;

                            spara.getTotal().Add(1, sendTradePara.getCashAmount());

                            if (sendTradePara.getPayTyp() == clsTradeTypeConst.TRADE_TYPE_CASH) {
                                spara.getCash().Add(1, sendTradePara.getCashAmount());
                            } else if (sendTradePara.getPayTyp() == clsTradeTypeConst.TRADE_TYPE_WX_QR) {
                                spara.getWeixin().Add(1, sendTradePara.getCashAmount());
                            } else if (sendTradePara.getPayTyp() == clsTradeTypeConst.TRADE_TYPE_AL_QR) {
                                spara.getAlipay().Add(1, sendTradePara.getCashAmount());
                            }

                            //clsArgs.getInst().saveStatistic(spara);
                            ThreadForBrd.getInstence().SetTradeMsg(spara);
                            ShowToast("保存统计信息到CPU");
                            break;
                        case clsCmdConst.CMD_HTTP_HEART_DATA_PARSE: //分析交易支付结果
                            if (msg.arg1 == 1) {
                                String res = (String) msg.obj;//HEART订单号,项目编号,支付类型,机器编号
                                String[] res_arr = res.split(",", -1);
                                if (res_arr.length > 1) {
                                    String orderid = res_arr[0].substring(5);
                                    int vid = clsToolBox.ParseInt(res_arr[3]);
                                    if (vid == clsArgs.getInst().getVenderid()) {
                                        clsSendTradeToPc net_trade = null;
                                        if (net_trade == null) {
                                            net_trade = new clsSendTradeToPc();
                                            net_trade.setTradeId(orderid);
                                            net_trade.setVendId(vid);
                                            net_trade.setDatetime(Calendar.getInstance());
                                            net_trade.setSlotid(clsToolBox.ParseInt(res_arr[1]));
                                            net_trade.setCashAmount(clsPublicPara.productlst.get(0).getPrice());
                                            net_trade.setPayTyp(clsToolBox.ParseInt(res_arr[2]));
                                        }

                                        this.obtainMessage(clsCmdConst.CMD_PC_TRANSFOR, net_trade).sendToTarget();
                                        getQrcodeTime = 0;
                                    }
                                } else {
                                    //解析事件
                                }
                            }


                            break;
                        case clsCmdConst.CMD_HTTP_SEND_HEART_FRAME: //延遲5秒發送一個心跳請求
                            int send_heart_tick = 5000;
                            sendEmptyMessageDelayed(clsCmdConst.CMD_HTTP_SEND_HEART_FRAME, send_heart_tick);
                            clsHttpFrame.SendHttpPollFrame();
                            break;
                        case clsCmdConst.ONE_SEC_TICK: // 一張小票延遲1秒打印出來
                            if (getQrcodeTime-- <= 0) {
                                if (clsPublicPara.productlst.size() > 0) {
                                    clsProductPara slot = clsPublicPara.productlst.get(0);
                                    int goodroadid = slot.getId();
                                    int price = slot.getPrice();
                                    int goodscount = 99;
                                    int pay_type = 0;
//                                    clsPublicPara.InitialOk = true;
                                    if (clsPublicPara.InitialOk) {
                                        clsHttpFrame.SendHttpQrcodeRequestFrame(goodroadid, price, goodscount, pay_type);
                                        getQrcodeTime = MaxGetQrcodeTime;
                                    }
                                }
                            }
                            sendEmptyMessageDelayed(clsCmdConst.ONE_SEC_TICK, 1000);
                            break;
                        case clsCmdConst.CMD_HTTP_FRESH_QRCODE:
                            //在蓝色小屏幕上显示二维码
                            // TODO: 2017-01-04 刷新二维码
                            if (msg.arg1 == 1) {
                                String res = (String) msg.obj;
                                System.out.println(res);
                                String[] res_arr = res.split(",", -1);
                                //clsQrcodeInfo qrcodepara=new  clsQrcodeInfo();
                                String al_qrcode = res_arr[0].substring(6);
                                System.out.println("al_qrcode=" + al_qrcode);
                                String wx_qrcode = res_arr[1];
                                System.out.println("wx_qrcode=" + wx_qrcode);
//                                Toast.makeText(MainActivity.this, al_qrcode, Toast.LENGTH_SHORT).show();

                                Drawable draw = null;

                                if (lAlEn) {
                                    draw = ContextCompat.getDrawable(clsPublicPara.activity, R.drawable.alipaylog);
                                    img_al_qrcode.setImageBitmap(QRCodeUtil.createQRImageBitmap(al_qrcode, img_al_qrcode.getWidth(), img_al_qrcode.getHeight(), draw));
                                }
                                if (lWxEn) {
                                    draw = ContextCompat.getDrawable(clsPublicPara.activity, R.drawable.wxlog);
                                    img_wx_qrcode.setImageBitmap(QRCodeUtil.createQRImageBitmap(wx_qrcode, img_wx_qrcode.getWidth(), img_wx_qrcode.getHeight(), draw));
                                }
                            } else {
                                // TODO: 2017/5/7 重新获取二维码
                            }
                            break;
                        case clsCmdConst.CMD_HTTP_PUSH_SLOT_PARA: //对比推送的位置
                            clsHttpFrame.SendHttpSlotSendFrame();
                            sendEmptyMessageDelayed(clsCmdConst.CMD_HTTP_PUSH_SLOT_PARA, 5 * 60000);
                            break;
                        case clsCmdConst.CMD_PC_TELL_NET_BREAK: //判断是否显示网络错误的的提示
                            if (!netstate) {
                                if ((boolean) msg.obj) {
                                    getQrcodeTime = 0;
                                    if (labFaultTips != null) {
                                        labFaultTips.setVisibility(View.GONE);
                                    }
                                }
                            } else {
                                if (!(boolean) msg.obj) {
                                    if (labFaultTips != null) {
                                        labFaultTips.setVisibility(View.VISIBLE);
                                    }
                                }
                            }
                            netstate = (boolean) msg.obj;
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        videoViewBox.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                // TODO Auto-generated method stub
                VedioNext();
                return true;
            }
        });
        videoViewBox.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer arg0) {
                // 播放下一首
                VedioNext();
            }
        });

        //初始化http请求参数
        clscvhttp.getInstance().init(clsArgs.getInst().getServerurl());
        //clscvhttp.getInstance().start();


        t_ins.setmMainHandler(mainHandler);


        ins.setParentHander(mainHandler);


        m_brd_Handler = t_ins.getmChildHandler();

        t_ins.start();

        clsPublicPara.MainHandler = mainHandler;
        //一秒后获取一个标记号
        mainHandler.sendEmptyMessageDelayed(clsCmdConst.ONE_SEC_TICK, 1000);

        //5秒后发送一个心的时间
        mainHandler.sendEmptyMessageDelayed(clsCmdConst.CMD_HTTP_SEND_HEART_FRAME, 5000);

        //5秒后发送一个查询请求
        mainHandler.sendEmptyMessageDelayed(clsCmdConst.CMD_PC_POLL, 5000);

        //一分钟后发送推送对比位置
        mainHandler.sendEmptyMessageDelayed(clsCmdConst.CMD_HTTP_PUSH_SLOT_PARA, 60000);
    }

    private ArrayList<clsProductPara> LoadProduct() {  //初始化项目和加载产品
        ArrayList<clsProductPara> productlst = new ArrayList<clsProductPara>();
        String[] lst = clsArgs.getInst().getProduct();

        for (int i = 0; i < lst.length; i++) {
            String src = "";
            try {
                src = new String(Base64.decode(lst[i], Base64.DEFAULT), CHAR_CODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!src.equals("")) {//不为""才添加产品
                Gson g = new Gson();
                clsProductPara product = g.fromJson(src, clsProductPara.class);
                productlst.add(product);
            }
        }
        return productlst;
    }


    private void VedioNext() { //下个视频
        ArrayList<String> lst = Vediolst;
        if (lst.size() > 0) {
            String filepath = lst.get(0);
            lst.remove(0);
            lst.add(filepath);

			/**/
            videoViewBox.pause();
            videoViewBox.setVideoPath(filepath);
            videoViewBox.start();

        }
    }

    public void butLog_OnClick(View view) {
        EnterSettingPage();
    }

    private void ShowVedio(String sd_path) {  //播放视频
        ArrayList<String> paths = new ArrayList<String>();
        File f = new File(sd_path + "/vedio");
        File[] files = f.listFiles(new VedioFilter());// 列出所有文件
        // 将所有文件存入list中
        if (files != null) {
            int count = files.length;// 文件个数
            for (int i = 0; i < count; i++) {
                File file = files[i];
                paths.add(file.getPath());
                System.out.println(file.getPath());
            }
        }
        if (paths.size() > 0) {
            Vediolst = paths;
            VedioNext();
        }
    }


    //进入到测试界面
    private void EnterSettingPage() {
        Intent intent = new Intent(MainActivity.this, Main2Activity.class);
        startActivity(intent);
    }

    public void videoView_ad_click(View view) {
        EnterSettingPage();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

        }
        return false;
    }

    /* 过滤文件类型 */
    class VedioFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            // 这里还可以设置其他格式的文件
            return (name.endsWith(".mp4") || name.endsWith(".MOV") || name.endsWith(".avi"));
        }
    }

    class ImgFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            // 这里还可以设置其他格式的文件
            return (name.endsWith(".gif") || name.endsWith(".jpg") || name.endsWith(".bmp") || name.endsWith(".png"));
        }
    }

}

